<template>
  <div class="drawerWrap add-classModel-drawer mx5">
    <div>
      <el-form
        :model="formOption"
        class="p-20px"
        label-width="100px"
        label-suffix="："
        :rules="rules"
        ref="formRef"
      >
        <el-form-item prop="assetCreateList" label="上传文件">
          <el-upload
            v-model:file-list="formOption.assetCreateList"
            drag
            :action="updateUrl"
            class="w-100%"
            multiple
            :headers="uploadHeaders"
            :on-success="uploadSuccess"
            :on-error="uploadError"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text"> 将文件拖至此处，或<em>点击上传</em> </div>
            <template #tip>
              <Icon icon="svg-icon:tips" />
              <span style="color: #cccccc"> 仅允许上传单个、批量文件或压缩包 </span></template
            >
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <div class="dialog-footer">
      <el-button type="primary" @click="submit">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { UploadFilled } from '@element-plus/icons-vue'
import * as apiTrainContent from '@/api/system/trainModel/trainContent'
import { getAccessToken, getTenantId } from '@/utils/auth'
const formRef = ref()
const updateUrl = import.meta.env.VITE_UPLOAD_URL
const props = defineProps(['params', 'closeOutDrawer'])
const fileList = ref([])
const formOption = reactive({
  assetCreateList: []
})
const fileListValidator = (rule: any, value: any, callback: any) => {
  if (formOption.assetCreateList.length === 0) {
    callback(new Error('请上传文件'))
  } else {
    callback()
  }
}
const rules = reactive({
  assetCreateList: [{ required: true, validator: fileListValidator, trigger: 'blur' }]
})
const submit = () => {
  formRef.value.validate().then((res) => {
    if (res) {
      formOption.assetCreateList = fileList.value.map((item) => {
        const arr = item.name.split('.')
        const type = arr[arr.length - 1]
        return {
          fileName: item.name,
          id: item.id,
          taskId: item.configId,
          fileId: item.configId,
          fileSize: item.size,
          fileType: type,
          filePath: item.path
        }
      })
      props.params.type === 'create'
        ? apiTrainContent
            .addContentModel({
              ...formOption,
              moduleTaskId: props.params.moduleTaskId
            })
            .then((res) => {
              if (res.code === 200) {
                ElMessage.success(`添加成功`)
                props.params.callBack()
                props.closeOutDrawer()
              } else {
                ElMessage.error(res.message)
              }
            })
        : apiTrainContent
            .editContentModel({
              ...formOption,
              moduleTaskId: props.params.moduleTaskId,
              id: props.params.id
            })
            .then((res) => {
              if (res.code === 200) {
                ElMessage.success(`追加文件成功`)
                props.params.callBack()
                props.closeOutDrawer()
              } else {
                ElMessage.error(res.message)
              }
            })
    }
  })
}
const cancel = () => {
  props.closeOutDrawer()
}
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})
const uploadError = (res: any): void => {
  ElMessage.error(res.message)
}
const uploadSuccess = (res: any): void => {
  let { data } = res
  if (data != null) {
    fileList.value.push(data)
    ElMessage.success('上传成功')
  }
  formOption.assetCreateList = formOption.assetCreateList.filter((item) => {
    if (item.response?.code != 200) {
      ElMessage.error(item.response?.message || '上传失败')
    }
    return item.response.code == 200
  })
  formRef.value.validate()
}
onMounted(() => {
  if (props.params.type === 'edit') {
    apiTrainContent.getContentDetail({ id: props.params.id }).then(({ data }) => {
      Object.keys(formOption).forEach((key) => {
        if (key == 'assetCreateList') {
          fileList.value = formOption.assetCreateList = []
        } else {
          formOption[key] = data[key]
        }
      })
      formOption.id = data.id
    })
  }
})
</script>

<style scoped lang="scss">
.add-classModel-drawer {
  .el-select {
    width: 100%;
  }
}
</style>
